package com.ktjy.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


@Component  //创建当前类的bean实例对象
@Aspect //标识当前类是切面类
public class PrinterAspect {

    private static final Logger log = LoggerFactory.getLogger(PrinterAspect.class);

    @Pointcut("execution(* com.ktjy.entity.Printer.print())")

    public void pointcut(){};

    @Before(value = "pointcut()")
    public void before(JoinPoint jp){
        //生成0-9的随机数
        int num = (int)(Math.random()*10);
        if(num<5){
            log.info("打印机自检通过");
        }else if(num >= 5 && num<7){
            throw new RuntimeException("打印机自检未通过,出现卡纸异常");
        }else {
            throw new RuntimeException("打印机自检未通过，出现墨盒无墨异常");
        }
    }

    @AfterReturning(returning = "result",value = "pointcut()")
    public void afterReturing(JoinPoint jp,Object result){
        log.info("打印成功");
    }


    @AfterThrowing(throwing = "e",value = "pointcut()")
    public void afterThrowing(JoinPoint jp,Throwable e){
        log.info("【PrinterAspect 异常抛出增强】模拟业务异常回滚事务，异常信息为："+e.getMessage());

    }
}
